import React, { useState, useEffect, useCallback } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { useTheme } from '../theme/ThemeContext';
import { Button } from './Button';
import { formatDuration } from '../utils/timeUtils';

interface TimerProps {
  onStop: (duration: number) => void;
}

export const Timer: React.FC<TimerProps> = ({ onStop }) => {
  const { theme } = useTheme();
  const [isRunning, setIsRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [seconds, setSeconds] = useState(0);
  const [startTime, setStartTime] = useState<Date | null>(null);

  useEffect(() => {
    let interval: NodeJS.Timeout;

    if (isRunning && !isPaused) {
      interval = setInterval(() => {
        setSeconds(prev => prev + 1);
      }, 1000);
    }

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [isRunning, isPaused]);

  const handleStart = useCallback(() => {
    setIsRunning(true);
    setStartTime(new Date());
  }, []);

  const handlePause = useCallback(() => {
    setIsPaused(true);
  }, []);

  const handleResume = useCallback(() => {
    setIsPaused(false);
  }, []);

  const handleStop = useCallback(() => {
    setIsRunning(false);
    setIsPaused(false);
    onStop(seconds);
    setSeconds(0);
    setStartTime(null);
  }, [seconds, onStop]);

  return (
    <View style={styles.container}>
      <Text style={[styles.timer, { color: theme.colors.text }]}>
        {formatDuration(seconds)}
      </Text>
      <View style={styles.buttonContainer}>
        {!isRunning ? (
          <Button title="开始" onPress={handleStart} />
        ) : (
          <>
            {!isPaused ? (
              <Button
                title="暂停"
                variant="secondary"
                onPress={handlePause}
                style={styles.button}
              />
            ) : (
              <Button
                title="继续"
                variant="secondary"
                onPress={handleResume}
                style={styles.button}
              />
            )}
            <Button
              title="停止"
              variant="outline"
              onPress={handleStop}
              style={styles.button}
            />
          </>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    padding: 20,
  },
  timer: {
    fontSize: 48,
    fontWeight: 'bold',
    marginBottom: 32,
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  button: {
    marginHorizontal: 8,
  },
}); 